<template>
  <div class="container">
    <el-form :inline="true" :model="filterData" class="search">
      <el-form-item>
        <!-- <el-input
          clearable
          placeholder="辖区搜索"
          v-model="searchWords.jurisdiction"
          style="width: 110px"
        /> -->

        <el-select
      v-model="searchWords.jurisdiction"
      placeholder="辖区搜索"
      style="width: 100px"
    >
      <el-option
        v-for="item in areaSelectList"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      />
    </el-select>


      </el-form-item>
      <el-form-item>
        <el-input
          clearable
          placeholder="预约单位搜索"
          v-model="searchWords.enterpriseName"
          style="width: 110px"
        />
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="searchWords.auditState"
          clearable
          placeholder="状态搜索"
          style="width: 100px"
        >
          <el-option value="1" label="审核中" />
          <el-option value="2" label="待培训" />
          <el-option value="3" label="已拒绝" />
          <el-option value="4" label="已培训" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="培训开始时间"
          end-placeholder="培训结束时间"
          value-format="YYYY-MM-DD"
          style="width: 250px"
        />
      </el-form-item>
      <!-- <el-form-item>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
          style="width: 200px"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button :icon="Search" @click="initList(1)" />
      </el-form-item>
    </el-form>
    <div class="table-contain">
      <Table
        ref="tableRef"
        height="100%"
        row-key="id"
        :columns="tableData.columns"
        v-loading="tableData.loading"
        :data="tableData.data"
      >
      <template #auditState="{ row }">
          <div :style="{color:renderColor(row.auditState)}">{{ getTranslate(auditList, "value", row.auditState, "label") }}</div>
        </template>
        <template #jurisdiction="{ row }">
          {{
            getTranslate(areaList, "code", row.jurisdiction, "name")
          }}
        </template>
        <template #category="{ row }">
          {{
            getTranslate(companyType, "code", row.category, "name")
          }}
        </template>
        <template #leturerName="{ row }">
          {{ row.leturerName }} {{ row.leturerPhone }}
        </template>
        
        <template #contactName="{ row }">
          <span>{{ row.contactName }} {{ row.phone }}</span>
        </template>
         
        <template #operation="{ row }">
          <el-button
            v-if="row.auditState == 1"
            plain
            type="warning"
            @click="handleFn(row)"
          >
            审核
          </el-button>
          <!-- <el-button
            v-if="row.auditState == 2"
            plain
            type="warning"
            @click="handleEdit(row)"
          >
            编辑
          </el-button> -->
          <el-button
            v-if="row.auditState == 2"
            plain
            type="success"
            @click="hadnleEnd(row, true)"
          >
            完成
          </el-button>
          <el-button
            v-if="row.auditState == 3"
            type="danger"
            plain
            @click="del(row)"
          >
            拒绝原因
          </el-button>
          <el-button
            v-if="row.auditState == 4"
            plain
            @click="toDetail(row)"
          >
            查看详情
          </el-button>

          <!-- <el-button
            plain
            @click="toDetail(row)"
          >
            查看详情
          </el-button> -->
        </template>
      </Table>
    </div>
    <Page
      :page-data="pageData"
      :total="tableData.total"
      @page-no-change="(pageNum) => (pageData.pageNum = pageNum)"
      @page-size-change="(pageSize) => (pageData.pageSize = pageSize)"
    />

    <HandleDialog
      v-model:visible="handleVisible"
      v-model:data="rowData"
      v-model:isDisabled="isDisabled"
      :parent-menu-option="tableData.data"
      @submit="initList"
    />

    <EditForm
      v-model:visible="editVisible"
      v-model:data="rowData"
      :parent-menu-option="tableData.data"
      @submit="initList"
    />

    <UploadImg
      v-model:visible="uploadVisible"
      v-model:data="rowData"
      :parent-menu-option="tableData.data"
      @submit="initList"
    />
    
    
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from "vue";
import Table from "@/components/pageTable/table";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Delete,
  Edit,
  Search,
  RefreshLeft,
  Position,
  View,
} from "@element-plus/icons-vue";
import Page from "@/components/pageTable/Page.vue";
import {
  deleteVideo,
  pageVideo,
  publishVideo,
  selectVideoList,
  topVideo,
  withdrawVideo,
} from "@/api/videoManage.ts";
import { getTranslate } from "@/util";
import { trainingInfoList } from "@/api/apply";
import { selectDicts, selectSysDictDataParentOrChilderById } from "@/api/system";
import HandleDialog from "./components/handleDialog.vue";
import EditForm from "./components/EditForm.vue";
import UploadImg from "./components/uploadImg.vue";
import router from "@/router";
import useUserStore from "@/store/useUserStore.ts";
import { selectUserById } from "@/api/user";

let rowData: any;
let filterData = reactive({ name: "" });
const tableRef = ref();
const date = ref<string[]>();
  
const isDisabled = ref<boolean>(false);
const handleVisible = ref<boolean>(false);
const editVisible = ref<boolean>(false);
const uploadVisible = ref<boolean>(false);
  const userStore = useUserStore();
const videoTypeList = ref<any[]>([]);
const areaList = ref<any[]>([]);
const areaSelectList = ref<any[]>([]);
const companyType = ref<any[]>([]);
const pageData = reactive({
  pageSize: 15,
  pageNum: 1,
});

const renderColor = (state) =>{
  switch(state){
    case 1:
      return '#e6a23c';
      break;
      case 2:
      return '#67c23a';
      break;
      case 3:
      return '#f56c6c';
      break;

      default:
      return '#333';
      break;

  }
}

const auditList = [
{ value: 1, label: '审核中' },
      { value: 2, label: '待培训' },
      { value: 3, label: '已拒绝' },
      { value: 4, label: '已培训' },
];
const searchWords = reactive({
  jurisdiction:"",
  startDate:"",
  endDate:"",
  enterpriseName:"",
  auditState:"",
});
const tableData = reactive({
  columns: [
  { label: "状态", prop: "auditState", width: 120, template: true },
    { label: "辖区", prop: "jurisdiction", width: 120, template: true },
    { label: "单位类别", prop: "category", width: 120, template: true },
    { label: "申请单位", prop: "enterpriseName", width: 150 },
    { label: "培训人数", prop: "number", width: 100, },
    { label: "申请人", prop: "contactName", width: 160,template: true },
    // { label: "主讲人", prop: "leturerName", width: 110,template: true },
    { label: "培训时间", prop: "trainingTime", width: 170,  },
    { label: "备注", prop: "remark", width: 170,  },
    { label: "创建时间", prop: "createdAt", width: 170,  },
    {
      label: "操作",
      prop: "operation",
      fixed: "right",
      template: true,
      align: "left",
      width:200,
    },
  ],
  loading: false,
  total: 0,
  data: [],
});

const toDetail = (row:any) => {
  router.push({
    path: "/trainDetail",
    query: {
      id: row.id
    },
  });
}

function handleFn(row:any){
  console.log(row)
  rowData = row;
  handleVisible.value = true
}

function handleEdit(row:any){
  console.log(row)
  rowData = row;
  editVisible.value = true
}

function hadnleEnd(row:any){
  console.log(row)
  rowData = row;
  uploadVisible.value = true
}

async function initList(page: number) {
  pageData.pageNum = page || 1;
  let params = {
    pageNum: pageData.pageNum || 1,
    pageSize: pageData.pageSize,
    ...searchWords,
  };
  tableData.loading = true;
  const { data, msg, success } = await trainingInfoList(params);
  if (!success) {
    ElMessage.error(msg);
    tableData.loading = false;
    return;
  }
  tableData.loading = false;
  tableData.data = data?.list;
  tableData.total = data?.total;
}

async function  getDictList(){
  const {data} =  await selectDicts()
  console.log(data[77])
  areaList.value = data[13]
  companyType.value = data[77]
}

function beforeChange(row: any) {
  return new Promise((resolve) => {
    ElMessageBox.confirm(
      `是否${row?.isTop == "1" ? "取消置顶" : "置顶"}?`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    ).then(async () => {
      const { success, msg } = await topVideo({
        id: row?.id,
        isTop: row?.isTop == 1 ? "2" : "1",
      });
      if (!success) {
        ElMessage.error(msg);
        return;
      }
      resolve(true);
      ElMessage.success("操作成功");
      await initList(1);
    });
  });
}

async function del(row: any) {
  ElMessageBox.confirm(row.auditReason, "拒绝原因", {
    confirmButtonText: "确定",
    showCancelButton:false
    // type: "warning",
  }).then(async () => {
    // const { success, msg } = await deleteVideo(row?.id);
    // if (!success) {
    //   ElMessage.error(msg);
    //   return;
    // }
    // ElMessage.success("操作成功");
    // await initList(1);
  });
}

async function getRelease(row: any) {
  ElMessageBox.confirm(`是否确认发布视频?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { success, msg } = await publishVideo({ id: row?.id });
    if (!success) {
      ElMessage.error(msg);
      return;
    }
    ElMessage.success("操作成功");
    await initList(1);
  });
}

async function getWithdrawVideo(row: any) {
  ElMessageBox.confirm(`是否确认撤回?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { success, msg } = await withdrawVideo({ id: row?.id });
    if (!success) {
      ElMessage.error(msg);
      return;
    }
    ElMessage.success("操作成功");
    await initList(1);
  });
}

async function getSelectVideoList() {
  const { success, msg, data } = await selectVideoList();
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  videoTypeList.value = data;
}

async function getSelectArae() {
  let userInfo = userStore.userData.userInfoDto
  const res =  await selectUserById({userId:userInfo.id})
  const { success, msg, data } =  await  selectSysDictDataParentOrChilderById(res?.data?.jurisdiction)
 if (!success) {
    ElMessage.error(msg);
    return;
  }
  areaSelectList.value = data;
  
}

onMounted(async () => {
  await initList(pageData.pageNum);
  await getSelectVideoList();
  await getDictList()
  await getSelectArae()
});

watch(date, (value) => {
  searchWords.startDate = value?.[0] ? `${value?.[0]}` : "";
  searchWords.endDate = value?.[1] ? `${value?.[1]}` : "";
});

watch(pageData, async () => {
  await initList(pageData.pageNum);
});
watch(searchWords, async () => {
  await initList(1);
});
</script>

<style scoped lang="scss">
@import "@/assets/styles/common";
</style>
